<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\CnDiagnoseStoreRequest;
use App\Models\CnDiagnose;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CnDiagnoseController extends ApiController
{
    public function index(Request $request)
    {
        $field = app('field')->get('diagnose.cn_diagnose.type');

        $cnDiagnoses = CnDiagnose::where('record_id', $request->input('record_id'))
                                 ->with('disease')
                                 ->get();

        $cnDiagnoses = $cnDiagnoses->map(function (CnDiagnose $cnDiagnose) use ($field) {
            $cnDiagnose['type'] = array_key_exists($cnDiagnose['type_id'], $field) ? $field[$cnDiagnose['type_id']] : '';
            return $cnDiagnose;
        });

        return $this->response($cnDiagnoses->toArray());
    }

    /**
     * 存中医诊断
     * @param \App\Http\Requests\CnDiagnoseStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(CnDiagnoseStoreRequest $request)
    {
        $input = $request->input();

        $result = CnDiagnose::create($input);

        if ($result) {
            return $this->hasData(['id' => $result->id]);
        } else {
            return $this->setMessage('执行错误，稍后再试。')->setCode(40004)->hasNoData();
        }
    }

    /**
     * 按病历ID或者诊断ID获取中医诊断
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Request $request)
    {
        $result = CnDiagnose::with('disease')->where(['id', $request->input('id')])->first();

        $diagnose = app('field')->get('diagnose.cn_diagnose');

        if ($result->type_id > 0) {
            $result['type'] = $diagnose['type'][$result->type_id];
        }

        $result['carry'] = array_intersect_key(
            $diagnose['carry'],
            array_flip($result['carry_key'])
        );

        return $this->response($result->toArray());
    }

    /**
     * Update the specified resource in storage.
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $this->updateValidation($request);

        $input = $request->except('id', 'record_id');

        if (isset($input['carry_key']) && !empty($input['carry_key'])) {
            $input['carry_key'] = implode(',', $input['carry_key']);
        }

        $result = CnDiagnose::where('id', $request->input('id'))->update($input);

        return $this->responseForUpdate($result);
    }

    /**
     * Remove the specified resource from storage.
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($id)
    {
        return $this->responseForDelete(CnDiagnose::select('id')->findOrFail($id)->delete());
    }

    protected function updateValidation(Request $request)
    {
        $diagnose = app('field')->get('diagnose.cn_diagnose');

        $this->validate($request, [
            'id'            => [
                'required', 'integer', 'min:1',
                Rule::exists('st_cn_diagnoses', 'id')->whereNull('deleted_at')
            ],
            'cn_disease_id' => [
                'required', 'integer', 'min:1',
                Rule::exists('st_cn_disease_dictionary', 'id')->whereNull('deleted_at')
            ],
            'type_id'       => [
                'integer', 'in:' . implode(',', $diagnose['type'])
            ],
            'carry_key.*'   => 'in:' . implode(',', $diagnose['carry'])
        ]);
    }
}
